package utils

import (
	"errors"
	"github.com/dgrijalva/jwt-go"
	"github.com/spf13/cast"
	"time"
)

var jwtSecret []byte

func secret() jwt.Keyfunc { //按照这样的规则解析
	return func(t *jwt.Token) (interface{}, error) {
		return jwtSecret, nil
	}
}

type Userinfo struct {
	Id      int    `json:"id"`
	Account string `json:"account"`
	Exp     int64  `json:"exp"`
}

func GenerateToken(user *Userinfo) (string, error) {
	claims := jwt.MapClaims{ //创建一个自己的声明
		"id":      user.Id,
		"account": user.Account,
		"exp":     user.Exp,
		"iat":     time.Now().Unix(),
	}
	var tokenClaims = jwt.NewWithClaims(jwt.SigningMethodHS256, &claims)
	token, err := tokenClaims.SignedString(jwtSecret)
	return token, err
}
func ParseToken(token string) (user *Userinfo, err error) {
	tokn, _ := jwt.Parse(token, secret())
	claim, ok := tokn.Claims.(jwt.MapClaims)
	if !ok {
		return nil, errors.New("解析错误")
	}
	if !tokn.Valid {
		return nil, errors.New("令牌错误")
	}
	return &Userinfo{
		Id:      cast.ToInt(claim["id"]),
		Account: cast.ToString(claim["account"]),
		Exp:     cast.ToInt64(claim["exp"]),
	}, nil
}

type WxUserinfo struct {
	Id  int   `json:"id"`
	Exp int64 `json:"exp"`
}

func GenerateWxToken(user *WxUserinfo) (string, error) {
	claims := jwt.MapClaims{ //创建一个自己的声明
		"id":  user.Id,
		"exp": user.Exp,
		"iat": time.Now().Unix(),
	}
	var tokenClaims = jwt.NewWithClaims(jwt.SigningMethodHS256, &claims)
	token, err := tokenClaims.SignedString(jwtSecret)
	return token, err
}
func ParseWxToken(token string) (user *WxUserinfo, err error) {
	tokn, _ := jwt.Parse(token, secret())
	claim, ok := tokn.Claims.(jwt.MapClaims)
	if !ok {
		return nil, errors.New("解析错误")
	}
	if !tokn.Valid {
		return nil, errors.New("令牌错误")
	}
	return &WxUserinfo{
		Id:  cast.ToInt(claim["id"]),
		Exp: cast.ToInt64(claim["exp"]),
	}, nil
}
